<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\SlideVerifyController;
use App\Models\Manage;
use App\Models\ManageLoginLog;
use App\Models\Permission;
use App\Validate\ManageInfoValidate;
use Illuminate\Http\Request;
use Kkokk\Poster\PosterManager;
use Mews\Captcha\Facades\Captcha;

/**
 * 后台登录界面
 */
class LoginController extends Controller
{

    public $request = null;
    public $validateObj = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->validateObj = new ManageInfoValidate();
    }

    /**
     * 后台管理员登录
     * @param account 账号
     * @param password 密码
     * @param captcha string  验证码  默认  5位
     * @param key_str  string 验证码字符串 （获取验证码时返回的key值）
     */
    public function login()
    {
        $app_expire_time = config('other.app_expire_time');
        if ($app_expire_time && $app_expire_time < date('Y-m-d')) {
            $app_expire_msg = config('other.app_expire_msg') ? config('other.app_expire_msg') : '试用已过期！';
            return  response()->json(['code' => 301, 'msg' => $app_expire_msg]); //使用过期，什么都不能使用
        }

        //  dump(request()->session()->all());
        //增加验证场景进行验证
        if (!$this->validateObj->scene('login')->check($this->request->all())) {
            return response()->json(['code' => 201,  'msg' => $this->validateObj->getError()]);
        }

        //再次验证验证码是否正确，验证器里面没有验证
        // if (!captcha_api_check($this->request->captcha, $this->request->key_str, 'flat')) {
        //     return response()->json(['code' => 201,  'msg' => '验证码输入错误']);
        // }
        $slideVerifyObj = new SlideVerifyController();
        if (!PosterManager::Captcha()->type($slideVerifyObj->type)->check($this->request->key_str, $this->request->captcha, 3)) {
            return response()->json(['code' => 207,  'msg' => '验证失败，请重试！']);
        }
        //验证密码
        $validate_password = validate_password($this->request->password);
        if ($validate_password !== true) {
            return response()->json(['code' => 201,  'msg' => $validate_password]);
        }

        $res = Manage::where('account', $this->request->account)->where('is_del', 1)->first();
        if (empty($res)) {
            return response()->json(['code' => 202,  'msg' => '此账号不存在']);
        }

        //判断账号是否被锁定
        $manageLoginLogModel = new ManageLoginLog();
        $is_lock_ed = $manageLoginLogModel->isLockEd($res['id']);
        if ($is_lock_ed) {
            return response()->json(['code' => 202,  'msg' => '此账号密码输入次数过多，已被锁定，请稍后重试']);
        }

        if ($res->password != md5($this->request->password)) {
            $is_lock = $manageLoginLogModel->isLock($res['id']);
            $is_lock = $is_lock ? 2 : 1;
            $manageLoginLogModel->insertLoginLog($res->id,  request()->ip(), 2, $is_lock); //添加错误日志
            return response()->json(['code' => 202,  'msg' => '密码输入不正确']);
        }

        /*生成token*/
        $tokenInfo = $this->getTokenExpireTime();
        $res->token = $tokenInfo['token'];
        $res->expire_time = $tokenInfo['expire_time'];
        $res->end_login_time = date('Y-m-d H:i:s');
        $res->end_login_ip = request()->ip();
        $result = $res->save();

        if (!$result) {
            return response()->json(['code' => 202,  'msg' => '登录失败,请稍后重试']);
        }

        //判断是否是初始密码  账号  加上 123 就是初始密码
        if ($res->password == $res->account . '123') {
            $is_modify_pwd = true; //初始密码，需要修改
        } else {
            $is_modify_pwd = false; //不是初始密码，需要修改
        }

        //添加登录日志
        $manageLoginLogModel->insertLoginLog($res->id,  request()->ip());

        $tokenInfo['is_modify_pwd'] = $is_modify_pwd; //返回是否需要修改密码

        $tokenInfo['username'] = $res['username'];
        $tokenInfo['account'] = $res['account'];
        $tokenInfo['way'] = $res['way'];

        //获取用户权限信息
        $permisstionModelObj = new Permission();
        $tokenInfo['permission'] = $permisstionModelObj->gerPermissionList($res->id);

        $tokenInfo['answer_activity_gift_type'] = config('other.answer_activity_gift_type'); // 获奖礼物类型（现在只要礼物）  1 红包  2 实物
        $tokenInfo['turn_activity_gift_type'] = config('other.turn_activity_gift_type'); // 获奖礼物类型（现在只要礼物）  1 红包  2 实物

        return response()->json(['code' => 200,  'msg' => '登录成功', 'content' => $tokenInfo]);
    }




    /**
     * 获取图形验证码   (需要现在中间件中开始session，不然会一直验证不通过)
     */
    public function getCaptcha()
    {
        //     $data = Captcha::src('flat');
        //     $data = Captcha::src();

        //     return response()->json(['code'=>200,  'msg'=>'获取成功','content'=>['captcha_url'=>$data]]);



        return response()->json(['code' => 200,  'msg' => '获取成功', 'content' => Captcha::create('flat', true)]); //flat 要与 验证器captcha里面的 值一致


    }

    /**
     * 获取用户token 及失效时间
     */
    public function getTokenExpireTime()
    {
        $data['token'] = get_guid();
        $data['expire_time'] = date("Y-m-d H:i:s", (time() + config('other.admin_token_refresh_time')));
        return $data;
    }
}
